//
//  SettingsManager.swift
//  GOFM
//
//  Created by siri on 2024/10/29.
//  Copyright © 2024 Glad. All rights reserved.
//  用户数据持久化
import Foundation

class SettingsManager {
    static let shared = SettingsManager()

    // 存储key
    private let tokenKey = "token"
    private let userInfoKey = "userinfo"
    
   
    // 设置token
    func setToken(_ token: String) {
        UserDefaults.standard.setValue(token, forKey: tokenKey)
    }

    // 读取token
    func getToken() -> String {
        return UserDefaults.standard.string(forKey: tokenKey) ?? ""
    }
    
    
    // 存储用户信息
    func setUserInfo(_ data: Token.Info) {
        UserDefaults.standard.setCodableObject(data, forKey:userInfoKey)
    }

    // 获取用户信息
    func getUserInfo() ->  Token.Info{
        return UserDefaults.standard.getCodableObject(Token.Info.self,with: userInfoKey) ?? Token.Info()
    }
   
}


// 存储对象信息
extension UserDefaults {
    /// 遵守Codable协议的set方法
    ///
    /// - Parameters:
    ///   - object: 泛型的对象
    ///   - key: 键
    ///   - encoder: 序列化器
    public func setCodableObject<T: Codable>(_ object: T, forKey key: String, usingEncoder encoder: JSONEncoder = JSONEncoder()) {

        let data = try? encoder.encode(object)
        set(data, forKey: key)
    }

    /// 遵守Codable协议的get方法
    ///
    /// - Parameters:
    ///   - type: 泛型的类型
    ///   - key: 键
    ///   - decoder: 反序列器
    /// - Returns: 可选类型的泛型的类型对象
    public func getCodableObject<T: Codable>(_ type: T.Type, with key: String, usingDecoder decoder: JSONDecoder = JSONDecoder()) -> T? {
        guard let data = value(forKey: key) as? Data else { return nil }
        return try? decoder.decode(type.self, from: data)
    }
}

